package pl.edu.pw.polygen.modeler.client.graph;

import java.util.ArrayList;
import java.util.List;

import pl.edu.pw.polygen.modeler.client.object.Vertex.VertexType;

public class VertexModel extends BaseModel implements IVertexModel{

	private static int counterId = 0;
	
	private int id;
	private double x = 0;
	private double y = 0;
	private List<IEdgeModel> edges;
	private VertexType vertexModelType;
	
	public VertexModel(){
		super();
		id = counterId++;
		edges = new ArrayList<IEdgeModel>();
	}
	
	public VertexModel(double x, double y,VertexType vertexType){
		this();
		this.x = x;
		this.y = y;
		vertexModelType = vertexType;
	}

	@Override
	public IEdgeModel addEdge(IVertexModel vertexModel, EdgeType type) {
		IEdgeModel edgeModel = new EdgeModel(this, vertexModel, type);
		int index = -1;
		//if((index = this.contains(edgeModel))==-1){
			this.edges.add(edgeModel);
			index = this.edges.size()-1;
		//}
		return this.edges.get(index);
	}
	
	@Override
	public void removeEdge(IVertexModel vertexModel) {
		for(IEdgeModel edge : edges){
			if(edge.getEnd()==vertexModel){
				edges.remove(edge);
				break;
			}
		}
	}

	@Override
	public void removeEdge(IVertexModel vertexModel, EdgeType type) {
		for(IEdgeModel edge : edges){
			if(edge.getEnd()==vertexModel && edge.getType()==type){
				edges.remove(edge);
				break;
			}
		}
	}

	
	
	@Override
	public IEdgeModel getEdge(IVertexModel endVertex) {
		for(IEdgeModel edgeModel : edges){
			if(edgeModel.getEnd()==endVertex){
				return edgeModel;
			}
		}
		return null;
	}

	@Override
	public List<IEdgeModel> getEdges() {
		return this.edges;
	}

	@Override
	public void setX(double x) {
		this.x = x;
		this.notifyObservers();
	}

	@Override
	public void setY(double y) {
		this.y = y;
		this.notifyObservers();
	}
	
	@Override
	public double getX() {
		return this.x;
	}

	@Override
	public double getY() {
		return this.y;
	}

	@Override
	public void setPosition(double x, double y){
		this.x = x;
		this.y = y;
		this.notifyObservers();
	}
	
	
	@Override
	public VertexType getType() {
		return vertexModelType;
	}
	
	@Override
	public int getId() {
		return id;
	}

	public VertexType getVertexModelType() {
		return vertexModelType;
	}

	public void setVertexModelType(VertexType vertexModelType) {
		this.vertexModelType = vertexModelType;
	}

	private int contains(IEdgeModel e){
		int i=0;
		for(IEdgeModel edge : edges){
			if(e.getBegin()==edge.getBegin() && e.getEnd()==edge.getEnd()){
				return i;
			}
			i++;
		}
		return -1;
	}
	
}
